package com.example.app.ui.Contact;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.example.app.ChatpageActivity;
import com.example.app.R;
import com.example.app.databinding.FragmentContactBinding;
import com.example.app.Websocket.AppDatabase;
import com.example.app.Entity.UserEntity;
import com.example.app.Entity.User;
import java.util.ArrayList;
import java.util.List;
public class ContactFragment extends Fragment {
    private FragmentContactBinding binding;
    private ContactAdapter adapter;
    private ListView listView;
    private User currentUser;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentContactBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        initViews(root);
        setupActionBar();
        loadFriendsFromDatabase();

        return root;
    }

    private void initViews(View root) {
        listView = root.findViewById(R.id.contactlv);
        listView.setOnItemClickListener(this::onItemClick);
        adapter = new ContactAdapter(requireContext(), new ArrayList<>());
        listView.setAdapter(adapter);
    }

    private void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        User selectedUser = (User) parent.getItemAtPosition(position);
        if (selectedUser != null) {
            navigateToChat(selectedUser);
        }
    }
    private void navigateToChat(User user) {
        SharedPreferences prefs = requireContext().getSharedPreferences(
                "user_credentials", Context.MODE_PRIVATE);
        prefs.edit()
                .putString("CurrentUserName", user.getNickname())
                .putString("CurrentUserid", user.getUserId())
                .apply();

        startActivity(new Intent(requireActivity(), ChatpageActivity.class));
    }
    private void setupActionBar() {
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        if (activity != null) {
            ActionBar actionBar = activity.getSupportActionBar();
            if (actionBar != null) {
                View customView = actionBar.getCustomView();
                TextView title = customView.findViewById(R.id.textView_title);
                title.setText("通讯录");
                customView.findViewById(R.id.imageView_logo).setOnClickListener(v ->
                        Log.d("Contact", "Left logo clicked"));
                customView.findViewById(R.id.imageView_logo2).setOnClickListener(v ->
                        Log.d("Contact", "Right logo clicked"));
            }
        }
    }
    private void loadFriendsFromDatabase() {
        new LoadFriendsTask().execute();
    }

    private class LoadFriendsTask extends AsyncTask<Void, Void, List<User>> {
        @Override
        protected List<User> doInBackground(Void... voids) {
            try {
                SharedPreferences prefs = requireContext().getSharedPreferences(
                        "user_credentials", Context.MODE_PRIVATE);
                String currentUserId = prefs.getString("current_user_id", "");
                AppDatabase db = AppDatabase.getInstance(requireContext());
                List<UserEntity> entities = db.friendDao().getFriendsForUser(currentUserId);
                System.out.println(entities);
                return convertToUserList(entities);
            } catch (Exception e) {
                Log.e("Contact", "Error loading friends", e);
                return new ArrayList<>();
            }
        }
        @Override
        protected void onPostExecute(List<User> friends) {
            if (friends.isEmpty()) {
                Toast.makeText(requireContext(),
                        "没有找到好友", Toast.LENGTH_SHORT).show();
            }
            adapter.updateData(friends);
        }
        private List<User> convertToUserList(List<UserEntity> entities) {
            List<User> users = new ArrayList<>();
            int[] presetAvatars = {
                    R.drawable.tx, R.drawable.xm, R.drawable.tx1,
                    R.drawable.tx2, R.drawable.tx3 // 添加更多预设头像
            };

            for (int i = 0; i < entities.size(); i++) {
                UserEntity entity = entities.get(i);
                User user = new User();
                user.setUserId(entity.getUserId());
                user.setNickname(entity.getNickname());
                user.setAvatarUrl("tx" + (i % 20));
                users.add(user);
            }
            return users;
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}